package com.carefree.bookmall.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.carefree.bookmall.common.utils.Constant;
import com.carefree.bookmall.common.vo.OrderPayVo;
import com.carefree.bookmall.config.AlipayConfig;
import com.carefree.bookmall.entity.Book;
import com.carefree.bookmall.entity.Order;
import com.carefree.bookmall.entity.User;
import com.carefree.bookmall.exception.CustomException;
import com.carefree.bookmall.service.BookService;
import com.carefree.bookmall.service.OrderService;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName:OrderController
 * @Description:
 * @Author Tengbin
 */
@Controller
@RequestMapping("/bookmall/order")
public class OrderController {

    @Resource
    public BookService bookService;

    @Resource
    public OrderService orderService;

    /**
     * 将书籍添加到购物车中
     *
     * @param bookId   书籍id
     * @param request  请求对象
     * @param response 响应对象
     */
    @GetMapping("/buy")
    @ResponseBody
    public String addBookToCart(@RequestParam("bookId") Integer bookId, HttpServletRequest request, HttpServletResponse response) throws CustomException {
        Order order = null;

        if (request.getSession().getAttribute(Constant.SESSION_ORDER) != null) {
            order = (Order) request.getSession().getAttribute(Constant.SESSION_ORDER);
        } else {
            order = new Order();
            order.setAmount(0);
            order.setTotal(0.00);
            request.getSession().setAttribute(Constant.SESSION_ORDER, order);
        }

        Book book = bookService.queryBookById(bookId);

        if (book.getStock() > 0) {
            order.addGoods(book);
            return "ok";
        }
        return "fail";
    }

    /**
     * 减少数量
     *
     * @param bookId   书籍id
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException
     */
    @PostMapping("/lessen")
    public void showBookByBookId(@RequestParam("bookId") Integer bookId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Order order = (Order) request.getSession().getAttribute(Constant.SESSION_ORDER);
        order.lessen(bookId);
        response.getWriter().print("ok");
    }

    /**
     * 删除加入的书籍信息
     *
     * @param bookId   书籍id
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException
     */
    @PostMapping("/delete")
    public void deleteBookByBookId(@RequestParam("bookId") Integer bookId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Order order = (Order) request.getSession().getAttribute(Constant.SESSION_ORDER);
        order.delete(bookId);
        response.getWriter().print("ok");
    }


    /**
     * 订单提交
     *
     * @param request
     * @return
     */
    @GetMapping("/submit")
    public String orderCommit(HttpServletRequest request) throws CustomException {
        User user = (User) request.getSession().getAttribute(Constant.SESSION_USER);
        if (user != null) {

            if ("北京市".equals(user.getAddress())) {
                request.setAttribute(Constant.FAIL_MESSAGE, "请输入收货地址后提交订单！");
                return "user_center";
            } else if ("新用户".startsWith(user.getRealName())) {
                request.setAttribute(Constant.FAIL_MESSAGE, "请输入真实姓名后提交订单！");
                return "user_center";
            } else {
                // 创建未支付订单
                Order order = (Order) request.getSession().getAttribute(Constant.SESSION_ORDER);

                order.setUserId(user.getId());
                order.setRealName(user.getRealName());
                order.setPhone(user.getPhone());
                order.setAddress(user.getAddress());
                order.setCreateTime(new Date());
                order.setStatus(5);
                orderService.addOrder(order);
                // 页面传值
                request.setAttribute("payOrder", order);
                // 移除购物车session
                //request.getSession().removeAttribute(Constant.SESSION_ORDER);

                return "order_confirm";
            }
        }
        request.setAttribute(Constant.FAIL_MESSAGE, "请登录后提交订单！");
        return "login";
    }


    /**
     * 确认订单并支付
     *
     * @return
     */
    @PostMapping("/prepay")
    public void confirmOrder(String orderId, HttpServletRequest request, HttpServletResponse response) throws CustomException, AlipayApiException, IOException {
        // 设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取session中的User信息
        User user = (User) request.getSession().getAttribute("usered");
        // 查询订单信息
        OrderPayVo orderPayVo = orderService.queryOrderPayInfo(orderId, user.getId());

        JSONObject bizContent = new JSONObject();
        // 订单号
        bizContent.put("out_trade_no", orderId);
        // 商品价格
        bizContent.put("total_amount", orderPayVo.getTotalAmount());
        // 商品名称
        bizContent.put("subject", orderPayVo.getSubject());
        // 商品码
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
        alipayTradePagePayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayTradePagePayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayTradePagePayRequest.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse alipayTradeWapPayResponse = alipayClient.pageExecute(alipayTradePagePayRequest);
        //response.getBody() 直接获取支付宝返回的页面，响应出去
        response.getWriter().print(alipayTradeWapPayResponse.getBody());
    }

    /**
     * 支付成功后异步通知
     *
     * @param request 支付成功后的返回请求
     * @throws CustomException
     */
    @GetMapping("/pay_return")
    public String aliNotifyPage(HttpServletRequest request) throws CustomException {
        // 获取支付宝返回数据
        Map<String, String[]> map = request.getParameterMap();
        // 下单生成的订单号
        String outTradeNo = map.get("out_trade_no")[0];

        // 如果支付宝接口返回为true，则更改支付类型及订单状态并减少购买商品的库存
        orderService.modifyOrderByIdAndUserId(outTradeNo, 1, 2);

        return "pay_return";
    }


    /**
     * 确认订单并付款
     *
     * @param orderId 订单号
     * @param request
     * @return
     */
    @GetMapping("/confirm/{orderId}")
    public String payOrder(@PathVariable String orderId, HttpServletRequest request) throws CustomException {
        User user = (User) request.getSession().getAttribute("usered");

        Order order = orderService.queryOrderById(orderId, user.getId());

        if (order != null) {
            request.setAttribute("payOrder", order);
            return "order_confirm";
        }
        return "redirect:/bookmall/order/myorders";
    }


    /**
     * 取消订单
     *
     * @param orderId
     * @return
     */
    @GetMapping("/cancel/{orderId}")
    @ResponseBody
    public boolean cancelOrder(@PathVariable String orderId) throws CustomException {
        return orderService.deleteOrderByOrderId(orderId);
    }

    /**
     * 确认收货
     *
     * @param orderId
     * @return
     */
    @PostMapping("/receipt/{id}")
    @ResponseBody
    public boolean confirmReceipt(@PathVariable String id, HttpServletRequest request) throws CustomException {
        return orderService.updateOrderStatus(id, 4);
    }


    /**
     * 用户自己删除订单(逻辑删除)
     *
     * @param orderId
     * @param request
     * @return
     */
    @GetMapping("/remove/{orderId}")
    @ResponseBody
    public boolean removeOrderById(@PathVariable String orderId, HttpServletRequest request) throws CustomException {
        User user = (User) request.getSession().getAttribute("usered");

        return orderService.removeOrderByIdAndUserId(orderId, user.getId());
    }

    /**
     * 我的订单
     *
     * @return
     */
    @GetMapping("/myorders")
    public String myOrders(HttpServletRequest request) throws CustomException {
        User user = (User) request.getSession().getAttribute("usered");
        if (ObjectUtils.isEmpty(user)) {
            return "redirect:/bookmall/index";
        }
        List<Order> orders = orderService.queryOrderByUserId(user.getId());
        request.setAttribute("orders", orders);
        return "user_orders";
    }

}
